<?php
class Screenshot_Adapter_PageGlimpse implements Screenshot_Adapter_Interface
{
    protected $_apiKey = '';
    
    protected $_sizeMap = array(
        'small'  => array(
            'width'  => 150,
            'height' => 108,
        ),
        'medium' => array(
            'width'  => 280,
            'height' => 202,
        ),
        'large'  => array(
            'width'  => 430,
            'height' => 310,
        )
    );
    
    const PAGE_GLIMPSE_URL = 'http://images.pageglimpse.com/v1/thumbnails';
     
    public function __construct($configOptions)
    {
        if (!isset($configOptions['apiKey']) || $configOptions['apiKey'] == '') {
            throw new Exception('Config option "apiKey" not set in config file for thumbnail adapter.');
        }
        
        $this->_apiKey = $configOptions['apiKey'];
    }
   
    
    public function generateScreenshot($url, $width, $height)
    {
        $serviceSize = 'large';
        
        foreach ($this->_sizeMap as $canonicalSize => $dimensions) {
            if ($dimensions['width'] == $width && $dimensions['height'] == $height) {
                $serviceSize = $canonicalSize;
            }
        }
        
        // check to see if the image exists already        
        $existsParams = array(
            'url'    => urlencode($url),
            'devkey' => $this->_apiKey,
            'size'   => $serviceSize
        );
                
        $existsUrl = $this->_buildUrl('/exists', $existsParams);
        
        $client = new Zend_Http_Client();
        $client->setUri($existsUrl);
        $client->setConfig(array('timeout' => 30));
        
        $response = $client->request();
        
        // If the return response is 200, the image exists, we can fetch it and return it.
        if ($response->getStatus() == '200') {
            $getParams = array(
                'devkey' => $this->_apiKey,
                'url'    => urlencode($url),
                'size'   => $serviceSize,
                'root'   => 'no',
            );
            
            $queueUrl = $this->_buildUrl('/', $getParams);
            
            $client->setUri($queueUrl);
            
            $response = $client->request();

            if ($response->getStatus() != '200') {
                return null;
            }
            
            $image = imagecreatefromstring((string)$response->getBody());
            
            $dst = imagecreatetruecolor($width, $height);
    
            // copy resized image to new canvas
            imagecopyresampled($dst, $image, 0, 0, 0, 0, $width, $height, $this->_sizeMap[$serviceSize]['width'], $this->_sizeMap[$serviceSize]['height']);  

            ob_start();
            imagejpeg($dst);
            
            return ob_get_clean();
        }
        
        //otherwise we must queue the image for generation and return null.  Upon additonal querying, the image will exist
        $queueParams = array(
            'devkey' => $this->_apiKey,
            'url'    => urlencode($url),
        );
        
        $queueUrl = $this->_buildUrl('/request', $queueParams);
        
        $client->setUri($queueUrl);
        
        $response = $client->request();
        return null;
    }
    
    protected function _buildUrl($path, $params)
    {
        $url = self::PAGE_GLIMPSE_URL . $path . '?';
        foreach ($params as $key => $value) {
            $url .= $key . '=' . $value . '&';
        }   

        return $url;
    }
}